
<template>
    <el-date-picker
      @change="dateChange"
      v-model="dateObj"
      type="daterange"
      :align="alignVal"
      unlink-panels
      value-format="yyyy-MM-dd HH:mm:ss"
      format="yyyy-MM-dd"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      :default-time="['00:00:00', '23:59:59']"
      :picker-options="pickerOptions"
    >
    </el-date-picker>
</template>

<script>
export default {
  model: {
    prop: 'param',
    event: 'cd'
  },
  props: {
    align: {
      type: String,
      default: 'right'
    },
    startTimeKey: {type: String, default: 'startDateTime'},
    endTimeKey: {type: String, default: 'endDateTime'},
    param: Object
  },
  data () {
    return {
      dateObj: [],
      alignVal: this.align,
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      }
    }
  },
  watch: {
    param: {
      handler (nVal, oVal) {
        if (nVal) {
          if (nVal.hasOwnProperty(this.startTimeKey)) {
            this.dateObj[0] = nVal[this.startTimeKey]
          }
          if (nVal.hasOwnProperty(this.endTimeKey)) {
            this.dateObj[1] = nVal[this.endTimeKey]
          }
        }
        if (this.dateObj) {
          this.dateObj = this.dateObj.filter(item => {
            return item !== null
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    dateChange (date) {
      const selectDate = {}
      if (date) {
        selectDate[this.startTimeKey] = date[0]
        selectDate[this.endTimeKey] = date[1]
      } else {
        selectDate[this.startTimeKey] = null
        selectDate[this.endTimeKey] = null
      }
      this.param = Object.assign(this.param, selectDate)
      this.$emit('cd', this.param)
      this.$emit('change', date)
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
